#include <unistd.h>
#include <cstring>
#include <cstdio>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
#include <pwd.h>
using namespace std;



//做一个简易的minshell
#define LEN 1024  //最大接收字符的数量
#define NUM 32 //最大接收命令个数
int main()
{
    char cmd[LEN];
    char* myargv[NUM];
    char hostname[32]; //主机名
    char pwd[128];  //当前目录
    while(1)
    {
        //准备好命令行
        struct passwd* ps = getpwuid(getuid());  //获取用户名字
        gethostname(hostname,sizeof(hostname)-1);  //主机名
        //获取当前目录
        getcwd(pwd,sizeof(pwd) -1);
        int len = strlen(pwd);
        //从最后开始找"/"
        char* p = pwd + len -1;
        while(*p != '/') --p;
        ++p; //跳过'/'
        //打印命令提示行
        printf("[%s@%s %s",ps->pw_name,hostname,p);
        //开始输入命令行，进行命令行获取
        fgets(cmd,LEN,stdin);
        //把最后一个置为0
        cmd[strlen(cmd)-1] = '\0';
        //切割命令
        myargv[0] = strtok(cmd," ");
        int i = 1;
        while(myargv[i] = strtok(NULL," ")) ++i;
        //创建子进程，进行进程替换
        pid_t id = fork();
        if(id == 0)
        {
            execvp(myargv[0],myargv);
            exit(1);
        }
        //father
        int status;
        int ret = wait(&status);
        if(ret > 0)
        {
            if(WEXITSTATUS(status))
            {
                cout << "wait child success , exitcode: " << WEXITSTATUS(status) <<endl;
            }
            else{
                //信号打断
                cout << "sign exit code : " << (status & 0x7F) << endl;
            }
        }
    }
    return 0;
}